package study.springcloud.breaker.sentinel.controller._1_flow;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import study.eggs.result.Result;
import study.eggs.result.Results;

import java.util.Map;

/**
 * fallback：若本接口出现未知异常，则调用fallback指定的接口。
 * blockHandler：若本次访问被限流或服务降级，则调用blockHandler指定的接口。
 */
@Slf4j
@RestController
public class _1_FlowController {

    @RequestMapping("/flow1")
    public Result echo() {
        Map<String, Object> data = Maps.newHashMap();
        data.put("msg", "echo1 echo1 echo1");
        return Results.ok(data);
    }

    /**
     * {
     *     "resource":"sayHi",
     *     "limitApp":"default",
     *     "grade":1,
     *     "count":1,
     *     "strategy":0,
     *     "controlBehavior":0,
     *
     *     "maxQueueingTimeMs":500,
     *     "warmUpPeriodSec":10
     *     "clusterMode":false,
     * }
     */
    public static void main(String[] args) {
        FlowRule rule = new FlowRule();

        rule.setResource("sayHi");   //资源名
        rule.setLimitApp("default"); //来源，若为 default 则不区分调用来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS); //限流级别（QPS 或 并发线程数）
        rule.setCount(1);                           //阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);                  //流控策略（直接、关联、链路）
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);  //流控效果（快速失败、Warm Up、排队等待）
        //
        rule.setWarmUpPeriodSec(1);
        rule.setMaxQueueingTimeMs(500);
        rule.setRefResource("/ressss");
        //是否集群
        rule.setClusterMode(false);

        log.info(">>>>>> {}", JSON.toJSONString(rule));
    }
}
